package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmall.dao.ProductCommentsMapper;
import com.qfedu.fmmall.entity.ProductComments;
import com.qfedu.fmmall.entity.ProductCommentsVO;
import com.qfedu.fmmall.service.ProductCommentsService;
import com.qfedu.fmmall.utils.PageHelper;
import com.qfedu.fmmall.vo.ResStatus;
import com.qfedu.fmmall.vo.ResultVO;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author liuyadi
 */
@Service
public class ProductCommentsServiceImpl implements ProductCommentsService {
    private ProductCommentsMapper productCommentsMapper;

    public ProductCommentsServiceImpl(ProductCommentsMapper productCommentsMapper) {
        this.productCommentsMapper = productCommentsMapper;
    }

    @Override
    public ResultVO listCommentsByProductId(String productId, int pageNum, int limit) {
//        List<ProductCommentsVO> productCommentsVOS = productCommentsMapper.selectCommentsByProductId(productId);
        // 1. 根据商品id查询总记录数
        Example example = new Example(ProductComments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId", productId);
        int count = productCommentsMapper.selectCountByExample(example);
        // 2. 计算出总页数（必须确定每一页显示多少条PageSize）
        int pageCount = count % limit == 0 ? count / limit : count / limit + 1;
        // 3. 查询当前页的数据（因为评论中需要用户信息，所以需要连表查询----自定义）
        int start = (pageNum - 1) * limit;
        List<ProductCommentsVO> productCommentsVOS = productCommentsMapper.selectCommentsByProductId2(productId, start, limit);
        ResultVO res = new ResultVO(ResStatus.OK.getCode(), "success", new PageHelper<ProductCommentsVO>(count, pageCount, productCommentsVOS));
        return res;
    }
}
